package demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;

@Path("/search")
public class SearchController2 extends Controller {
	public void index() {
    	render("search.html");
    }
	
	public void search() throws IOException{
		String jsonData = getRawData();
		jsonData = URLDecoder.decode(jsonData, "UTF-8");
    	JSONObject jo = JSONObject.parseObject(jsonData);
    	String keyword=jo.getString("keyword").trim();
    	String ids=jo.getString("ids");
    	String names=jo.getString("names");
    	//System.out.println(names);
    	String[] stja=keyword.split(" ");
    	
    	String[] idja=null;//search页面的症状
    	if(!ids.equals("")){
    		ids=ids.substring(1, ids.length()-1);
    		idja=ids.split("@@");
    	}
    	
    	String[] nameja=null;//search页面的症状
    	if(!names.equals("")){
    		names=names.substring(1, names.length()-1);
    		nameja=names.split("@@");
    	}
    	
    	String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
		File folder = new File(path);
		JSONArray ja=new JSONArray();
		traverse(folder,path,stja,ja,idja);
		changecontent(path,ja);
		setmark(ja,stja,nameja);
		
		Collections.sort(ja, new Comparator<Object>() {
		    @Override
		    public int compare(Object o1, Object o2) {
		        // 将Object对象转换为JSONObject进行比较
		        int num1 = ((JSONObject)o1).getIntValue("num");
		        int num2 = ((JSONObject)o2).getIntValue("num");
		        return Integer.compare(num2, num1);
		    }
		});
		
		//System.out.println(ja);
		renderJson((JSONObject) JSONObject.parse("{'res':'ok','data':"+ja.toJSONString()+"}"));
	}
	
	private void setmark(JSONArray ja,String[] stja,String[] nameja){
		for(int i=0;i<ja.size();i++){
			JSONObject jo=ja.getJSONObject(i);
			String remark=jo.getString("remark");
			String content=jo.getString("content");
			String bq=jo.getString("bq");
			if(stja.length>0&&!stja[0].equals("")){
				for (String s : stja) {
					remark = remark.replaceAll(s, "<mark>"+s+"</mark>");
					content = content.replaceAll(s, "<mark>"+s+"</mark>");
                }
			}
			jo.put("remark", remark);
			jo.put("content", content);
			
			///////////////////////////////////////////
			if(null!=nameja){
				for (String s : nameja) {
					bq = bq.replaceAll("@"+s+"@", "@<mark>"+s+"</mark>@");
				}
			}
			///////////////////////////////////////////
			jo.put("bq", bq.replaceAll("@", " "));
		}
	}
	
	private void traverse(File folder,String path,String[] stja,JSONArray ja,String[] idja) throws IOException {
	    
        if (folder.isDirectory()) {
            File[] files = folder.listFiles();
            for (File file : files) {
                traverse(file,path,stja,ja,idja);
            }
        } else {
        	String allname=folder.getName();
        	if(allname.endsWith("_bq.txt")){
        		String bookname=allname.substring(0, allname.length()-7);
        		String filePath=path+"/"+bookname+"/"+bookname+"_bq.txt";
            	
            	String fileContent = readFile(filePath);
            	
            	Pattern pattern = Pattern.compile("\\{([^}]*)\\}");
                Matcher matcher = pattern.matcher(fileContent);
                while (matcher.find()) {
                	String findst=matcher.group();
                    JSONObject jo=JSONObject.parseObject(findst);
                    jo.put("bookname", bookname);
                    jo.put("num", 0);
					///////////////////////////////////////////////////bqid
					String bqid=jo.getString("bqid");
					if(idja!=null){
						boolean flagid=false;
						int cnum=0;
						for (String s : idja) {
							if(bqid.contains("@"+s+"@")){
								flagid=true;
								cnum++;
							}
						}
						if(flagid){
							jo.put("num", cnum);
							ja.add(jo);
							continue;
						}
					}
					////////////////////////////////////////////////////
                    
                    if(stja.length>0&&!stja[0].equals("")){
	                    //////////////////////////////////////////////////remark
	                    String remark=jo.getString("remark");
	                    boolean flag=true;
	                    for (String s : stja) {
	                    	if(!remark.contains(s)){
	                    		flag=false;
	                    		break;
	                    	}
	                    }
	                    if(flag){
	                    	ja.add(jo);
	                    	continue;
	                    }
	                    /////////////////////////////////////////////////content
	                    String content=jo.getString("content");
	                    boolean flagcontent=true;
	                    for (String s : stja) {
	                    	if(!content.contains(s)){
	                    		flagcontent=false;
	                    		break;
	                    	}
	                    }
	                    if(flagcontent){
	                    	ja.add(jo);
	                    	continue;
	                    }
                    }
                    
                }
                
        	}
            
        }
    }
	
	private void changecontent(String path,JSONArray ja) throws IOException{
		String olebookname="";
		String oricontent="";
		for(int i=0;i<ja.size();i++){
			JSONObject jo=ja.getJSONObject(i);
			String id=jo.getString("id");
			String bookname=jo.getString("bookname");
			if(!olebookname.equals(bookname)){
				olebookname=bookname;
				String filePath=path+"/"+olebookname+"/"+olebookname+".txt";
				oricontent = readFile(filePath);
			}
			String str = new String("书签".getBytes("gbk"), "utf-8");
			String start="\"getsq("+id+",'"+olebookname+"')\">"+str+"</span>----&gt;</div>";
			String end="<div id=\""+id+"_1\"";
			String content=oricontent.substring(oricontent.indexOf(start)+start.length(), oricontent.indexOf(end));
			jo.put("content", content);
		}
	}
	
	private static String readFile(String filepath) throws IOException {
        StringBuilder fileContent = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filepath),"utf-8"));
        
        String line = reader.readLine();
        while (line != null) {
            fileContent.append(line);
            line = reader.readLine();
        }
        reader.close();

        return fileContent.toString();
    }
	
	

	
}
